package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.exception.BaseException;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO turnoverStat(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        // 如果开始日期与结束日期不相同
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 计算每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Map<String, Object> map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.turnoverStat(map);

            // 若是营业额为null，则设置为0.0
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO userStat(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        // 如果开始日期与结束日期不相同
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 计算每天的用户总数和每天新增的用户数
        List<Integer> userNumList = new ArrayList<>();
        List<Integer> newUserNumList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Map<String, Object> map = new HashMap<>();
            map.put("endTime", endTime);
            Integer userNum = userMapper.userStat(map);
            // 若是用户总数为null，则设置为0
            userNum = userNum == null ? 0 : userNum;
            userNumList.add(userNum);

            map.put("beginTime", beginTime);
            Integer newUserNum = userMapper.userStat(map);
            // 若是新用户总数为null，则设置为0
            newUserNum = newUserNum == null ? 0 : newUserNum;
            newUserNumList.add(newUserNum);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(userNumList, ","))
                .newUserList(StringUtils.join(newUserNumList, ","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO orderStat(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        // 如果开始日期与结束日期不相同
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 计算每天的订单总数和每天的有效订单数
        List<Integer> orderNumList = new ArrayList<>();
        List<Integer> validOrderNumList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Map<String, Object> map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            Integer orderNum = orderMapper.orderStat(map);
            // 若是订单总数为null，则设置为0
            orderNum = orderNum == null ? 0 : orderNum;
            orderNumList.add(orderNum);

            // 有效订单指已完成的订单
            map.put("status", Orders.COMPLETED);
            Integer validOrderNum = orderMapper.orderStat(map);
            // 若是有效订单数为null，则设置为0
            validOrderNum = validOrderNum == null ? 0 : validOrderNum;
            validOrderNumList.add(validOrderNum);
        }

        // 统计订单总数
        Integer sum4OrderNum = orderNumList.stream().reduce(Integer::sum).get();
        // 统计有效订单总数
        Integer sum4ValidOrderNum = validOrderNumList.stream().reduce(Integer::sum).get();
        // 订单完成率 = 有效订单总数 / 订单总数 * 100%
        Double completedRate = 0.0;
        if(sum4OrderNum != 0){
            completedRate = sum4ValidOrderNum * 1.0 / sum4OrderNum;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderNumList, ","))
                .validOrderCountList(StringUtils.join(validOrderNumList, ","))
                .totalOrderCount(sum4OrderNum)
                .validOrderCount(sum4ValidOrderNum)
                .orderCompletionRate(completedRate)
                .build();
    }

    /**
     * 销售排名top10
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO salesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        // 计算统计期间菜品/套餐的销量--状态是已完成的
        Map<String, Object> map = new HashMap<>();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("status", Orders.COMPLETED);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.salesTop10(map);
        List<String> nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 导出运营报表
     * @param response
     */
    public void export(HttpServletResponse response) {
        // 1.获取需要展示的数据(30天前 -- 昨天)
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        // 获取运营概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(beginDate, LocalTime.MIN),
                LocalDateTime.of(endDate, LocalTime.MAX));

        // 2.读取Excel模板
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(is);
            XSSFSheet sheet = excel.getSheetAt(0);

            // 3.在模板对应处填充数据
            // 3.1填充运营概率数据
            XSSFRow row = sheet.getRow(1);
            row.getCell(1).setCellValue("日期：" + beginDate + " 至 " + endDate);
            row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            // 3.2填充运营明细数据
            for(int i = 0; i < 30; i++){
                LocalDate date = beginDate.plusDays(i);
                BusinessDataVO tempBusinessDataVO = workspaceService.getBusinessData(
                        LocalDateTime.of(date, LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(tempBusinessDataVO.getTurnover());
                row.getCell(3).setCellValue(tempBusinessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(tempBusinessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(tempBusinessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(tempBusinessDataVO.getNewUsers());
            }

            // 4.通过浏览器下载文件
            ServletOutputStream os = response.getOutputStream();
            excel.write(os);

            // 5.关闭资源
            os.close();
            excel.close();
        } catch (IOException e) {
            throw new BaseException("运营数据文件生成失败，请联系系统管理员！");
        }
    }
}
